package leetcode.秋招.shopee;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：zsy
 * @date ：Created 2021/7/19 14:48
 * @description：
 */
public class 最小覆盖子字符串 {
    public static void main(String[] args) {

    }

    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.findMinOverrideSubString("abcd", "bc"));
    }

    public class Solution {
        /**
         * Note: 类名、方法名、参数名已经指定，请勿修改
         * <p>
         * <p>
         * find min override sub string
         *
         * @param source string字符串
         * @param target string字符串
         * @return string字符串
         */
        public String findMinOverrideSubString(String source, String target) {
            String t = target;
            String s = source;
            Map<Character, Integer> need = new HashMap<>();
            Map<Character, Integer> window = new HashMap<>();
            for (char c : t.toCharArray()) need.put(c, need.getOrDefault(c, 0) + 1);
            int i = 0, j = 0, start = 0, match = 0, len = Integer.MAX_VALUE;
            while (j < s.length()) {
                char c1 = s.charAt(j);
                j++;
                if (need.containsKey(c1)) {
                    window.put(c1, window.getOrDefault(c1, 0) + 1);
                    if ((int) need.get(c1) == (int) window.get(c1)) match++;
                }
                while (match == need.size()) {
                    if (j - i < len) {
                        start = i;
                        len = j - i;
                    }
                    char c2 = s.charAt(i);
                    i++;
                    if (need.containsKey(c2)) {
                        window.put(c2, window.getOrDefault(c2, 0) - 1);
                        if ((int) need.get(c2) > (int) window.get(c2)) match--;
                    }
                }
            }
            if (len == Integer.MAX_VALUE) return "";
            else return s.substring(start, start + len);
        }
    }
}
